<?php


namespace app\common\cachemodel;


use app\common\model\BaseCache;
use Exception;
use think\Log;
use XznsTools\cache\CacheManage;

class MiniUser extends BaseCache
{
    private const LOG_PRE = '小程序MiniUser Model 异常：';

    protected $table = 'wechat_backup_07_18_14_43_00.mini_user';
    protected $cacheModel = 'mini.user';

    /**
     * 添加小程序用户
     * @param $map
     * @return int|string
     */
    public function SavaData($map)
    {
        try
        {
            $id = $this->insertGetId($map);
        }
        catch (Exception $e)
        {
            Log::write(self::LOG_PRE . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            $id = 0;
        }

        return $id;
    }


    /**
     * 缓存获取小程序用户信息
     * @param $third_id
     * @param string $mini_type
     * @return array|bool|mixed
     * @throws Exception
     */
    public function getMiniInfo($third_id, $mini_type = '')
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $third_id . '-' . $mini_type)->getDataAndSet(function () use ($mini_type, $third_id)
        {
            return $this->getMiniInfoFromDms($third_id, $mini_type);
        });

        return $data;
    }

    /**
     * 数据库获取小程序用户信息
     * @param $param
     * @param string $mini_type
     * @return array|mixed
     */
    public function getMiniInfoFromDms($param, $mini_type = '')
    {
        //$type 1=>$id,2=>unionid,3=>$openid;
        $type = $this->getTypeFromMiniType($mini_type);
        switch ($type)
        {
            case 1:
                $where = ['id' => $param];
                break;
            case 2:
                $where = ['unionid' => $param, 'mini_type' => $mini_type];
                break;
            case 3:
                $where = ['openid' => $param, 'mini_type' => $mini_type];
                break;
            default:
                return [];
                break;
        }
        try
        {
            $data = $this->where($where)->column('id,openid,unionid,access_token,expires_in');
            $data = current($data);
        }
        catch (Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    /**
     * 通过 小程序类型 获取存入的唯一id类型
     * @param $mini_type
     * @return int $type 1=>$id,2=>unionid,3=>$openid;
     */
    public function getTypeFromMiniType($mini_type): int
    {
        $type = 0;
        switch ($mini_type)
        {
            case 'ALIPAY':
                $type = 3;
                break;
            case 'QQ':
                $type = 2;
                break;
            case 'WEAPP':
                $type = 2;
                break;
            case 'TT':
                $type = 3;
                break;
            case 'SWAN':
                $type = 2;
                break;
        }
        return $type;
    }
}
